<template>
  <div>
    <!-- 文件上传对话框 -->
    <DFModal
      ref="basicImportModalRef"
      class="basicModal"
      :title="Ititle"
      :subBtuText="isImportData ? 'import' : 'primary'"
      @on-close="clearFileList"
      @register="modalRegister"
      @on-ok="submitFileForm"
    >
      <template #default>
        <div :class="['upload-dialog-tip', `${isImportData ? 'import-dialog-tip' : ''}`]">
          <div v-if="!isImportData" class="content-left">
            <div>
              <i class="el-icon-warning"></i>
              {{ t('common.upload.note') }}
            </div>
          </div>
          <ul class="content-right">
            <li v-for="(item, key) in computedUploadTipList" :key="key">
              {{ tipFormat(item.tip) }}
              <span
                v-if="item.downloadTemplate"
                :class="['import-template', language === 'zh' ? '' : 'break-word']"
                @click="downloadImportTemplateFn"
              >
                {{ t('common.upload.downloadImportTemplate') }}
              </span>
            </li>
          </ul>
        </div>
        <div class="up-box">
          <n-upload
            ref="uploadDialog"
            :accept="computedFileType"
            directory-dnd
            :multiple="!isImportData"
            :max="computedLimit"
            :default-upload="!isImportData"
            :action="computedUploadFileUrl"
            :custom-request="customRequest"
            :headers="headers"
            :on-before-upload="
              (file) => {
                return handleBeforeUpload(file);
              }
            "
            @change="handleChange"
            @finish="finishFn"
            @remove="handleFileRemove"
            @error="handleUploadError"
          >
            <n-upload-dragger>
              <img class="upload-icon" src="@/assets/svg/upload.svg" />
              <div class="upload-text">
                {{ $t('common.upload.dragFile') }}
                <span class="import-template">{{ $t('common.upload.clickUpload') }}</span>
              </div>
            </n-upload-dragger>
          </n-upload>
        </div>
      </template>
    </DFModal>
  </div>
</template>

<script lang="ts" setup>
  import { useRoute } from 'vue-router';
  import { storage } from '@/utils/Storage';
  import { t } from '@/i18n';
  import { useMessage, UploadCustomRequestOptions, NUpload, NUploadDragger } from 'naive-ui';
  import { useMixins } from '@/hooks/useMixins';
  import { DFModal, useModal } from '@/components/DFModal';
import {
  downLoadFile,
  // downLoadFile2
} from '@/api/common/index';

  import { http } from '@/utils/http/axios';

  const { language, routerPage, downloadNameFn } = useMixins();
  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});

  let token = storage.get('access_token') || '';
  type Props = {
    isImportData?: boolean; // 是否是导入
    uploadTipList?: Array<any>; // 文件提示内容
    uploadUrl?: string; // 上传地址
    fileSize?: number; // 文件大小
    fileType?: any; // 文件类型
    limit?: number; // 文件数量
    otherFileLimit?: any; //其他特定文件大小，数量限制
    uploadedFiles?: Array<any>; //已上传的文件集合
    importTemplateFileType?: string; //下载模版文件类型
    importTemplateFileName?: string; //下载模版文件名称
  };

  const props = withDefaults(defineProps<Props>(), {
    isImportData: () => false,
    uploadTipList: () => [],
    uploadUrl: () => '',
    fileSize: () => 10,
    fileType: () => ['rar', 'zip', 'doc', 'docx', 'pdf', 'jpg', 'jpeg', 'png', 'bmp'],
    limit: () => 10,
    otherFileLimit: () => [
      { name: t('common.upload.video'), type: ['mp4', 'rmvb', 'avi'], size: 50, limit: 1 },
    ],
    uploadedFiles: () => [],
    importTemplateFileType: () => '',
    importTemplateFileName: () => '',
  });
  const emit = defineEmits(['getAttachmentList', 'register']);

  const route: any = toRaw(useRoute());
  const Ititle = ref('');

  // 全部文件列表
  const fileList: any = ref([]);
  const headers = ref({
    Authorization: 'Bearer ' + token,
  });

  const downloadImportRequest = ref(false);

  const uploadDialog: any = ref(null);
  const message = useMessage();
  // const openDialog = () => {
  //   open.value = true;
  // };

  const tipFormat = (val) => {
    // 如果带了数字, '、', '.'的，则去掉，序号用li的list-style: decimal来显示
    return !isNaN(parseInt(val[0])) ? val.slice(2) : val;
  };

  const computedUploadTipList = computed(() => {
    if (props.uploadTipList && props.uploadTipList.length) {
      return props.uploadTipList;
    }
    return props.isImportData
      ? [
          {
            tip: t('common.upload.importTip1'),
            downloadTemplate: true,
          },
          { tip: t('common.upload.importTip2') },
        ]
      : [
          { tip: t('common.upload.uploadTip1') },
          { tip: t('common.upload.uploadTip2') },
          { tip: t('common.upload.uploadTip3') },
        ];
  });

  const computedFileType = computed(() => {
    let list = '.xls,.xlsx';
    if (!props.isImportData) {
      return props.fileType.map((item) => '.' + item).join(',');
    }
    return list;
  });

  const computedLimit = computed(() => {
    return props.isImportData ? 1 : props.limit;
  });

  const computedUploadFileUrl = computed(() => {
    if (props.uploadUrl) {
      return props.uploadUrl;
    }

    const urlMap = {
      standardProject: '/crm/bmsMstTestProject/importExcel', // 点巡检项目导入地址
      standardProgramme: '/crm/bmsTblTestPlan/importExcel', // 点巡检方案导入地址
      aqlStandard: '/crm/qmMstAqlStandard/importExcel', // aql标准导入地址
    };
    if (props.isImportData && urlMap[routerPage]) {
      return urlMap[routerPage];
    }

    return '/oss/file/upload';
  });

  const computedImportTemplateFileName = computed(() => {
    const { meta = {} }: any = route;

    const { title = '' } = meta.value;
    if (props.importTemplateFileName) {
      return props.importTemplateFileName;
    }

    if (routerPage.includes('iotProductEdit')) {
      // IOT 产品管理 批量导入功能点
      return '批量导入功能点模板';
    }

    return `${title ? t('route.' + title) : ''}导入模板`;
  });
  const computedImportTemplateFileType = computed(() => {
    if (props.importTemplateFileType) {
      return props.importTemplateFileType;
    }
    const fileTypeMap = {
      maintainProjectManger: '0', // 保养项目管理模板
      equipMaintainManagement: '1', // 设备保养项目管理模板
      standardProject: '2', // 点巡检项目导入模板
      standardProgramme: '3', // 点巡检方案导入模板
      aqlStandard: '4', // aql标准导入模板
      collectionParamsManagement: '5', // 采集参数导入模板
      iotProductEdit: '7', // IOT 产品管理 批量导入功能点
    };
    return fileTypeMap[routerPage] || '0';
  });

  // const computedImportTemplateDownloadName = computed(() => {
  //   const fileNameMap = {
  //     zh: {
  //       pointPatrolInspectionStandard: '点巡检标准导入模板.xlsx', // 点巡检标准导入模板
  //       maintenanceStandard: '保养标准导入模板.xlsx', //保养标准导入模板
  //       partsLedger: '配件档案导入模板.xlsx', //配件档案导入模板
  //     },
  //     en: {
  //       pointPatrolInspectionStandard: 'import_point_inspection_standards_en_us.xlsx', // 点巡检标准导入模板
  //       maintenanceStandard: 'maintenance_standard_introduction_en_us.xlsx', //保养标准导入模板
  //       partsLedger: 'template_for_importing_accessory_en_us.xlsx', //配件档案导入模板
  //     },
  //   };
  //   return fileNameMap[language.value][routerPage] || null;
  // });

  const submitFileForm = async () => {
    if (!fileList.value.length) {
      message.error(t('common.upload.plsChooseFile'));
      setSubLoading(false);
      return;
    }

    //个数超出限制提示
    if (!props.isImportData && props?.otherFileLimit?.length) {
      let sameTypeFiles = {};
      props.otherFileLimit.map((item) => {
        [...(props.uploadedFiles || []), ...fileList.value].map((file) => {
          let fileTypes = file.fileType.split('/')[1] || file.fileType.split('/')[0];
          if (file?.fileName.lastIndexOf('.') > -1) {
            fileTypes = file?.fileName.slice(file?.fileName.lastIndexOf('.') + 1);
          }
          fileTypes = fileTypes.toLowerCase();
          if (item.type.includes(fileTypes)) {
            if (sameTypeFiles[item.name]) {
              sameTypeFiles[item.name]++;
            } else {
              sameTypeFiles[item.name] = 1;
            }
          }
        });
      });
      const overType = props.otherFileLimit.find(
        (item) => item.limit && sameTypeFiles[item.name] > item.limit
      );
      if (overType) {
        message.error(
          t(`common.upload.overLimitTip`, { name: overType.name, limit: overType.limit })
        );
        setSubLoading(false);
        return false;
      }
    }

    if ((props.uploadedFiles || []).concat(toRaw(fileList.value)).length > computedLimit.value) {
      message.error(
        t(`common.upload.overLimitTip`, {
          name: t('common.upload.file'),
          limit: computedLimit.value,
        })
      );
      setSubLoading(false);
      return false;
    }
    try {
      let newArr: any = [];
      fileList.value.forEach((item, key) => {
        const materItem = {
          ...item,
          index: key + 1,
        };
        if (materItem.status) {
          delete materItem.status;
        }
        newArr.push(materItem);
      });
      if (props.isImportData) {
        if (uploadDialog.value) {
          await uploadDialog.value.submit();
        }
      } else {
        emit('getAttachmentList', newArr);
      }
    } catch (e) {
      console.log(e);
    }
  };
  /** 上传相关 */
  //文件校验
  const checkFileTypeFn = (file) => {
    //校验文件类型
    let fileExtension = '';
    if (file?.name.lastIndexOf('.') > -1) {
      fileExtension = file?.name.slice(file?.name.lastIndexOf('.'));
    }
    const fileTypeList = unref(computedFileType).split(',');
    const isTypeOk = fileTypeList.some((type) => {
      if (file?.type.toLowerCase().indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.toLowerCase().indexOf(type) > -1) return true;
      setSubLoading(false);
      return false;
    });
    if (!isTypeOk) {
      message.error(
        `${t('common.tipMsg.fileUploadTipFirst')}${fileTypeList.join(' ')}${t(
          'common.tipMsg.fileUploadTiplast'
        )}`
      );
      setSubLoading(false);
      return false;
    }

    // 校检文件大小
    if (props?.otherFileLimit?.length) {
      const overFile = props.otherFileLimit.find(
        (item) =>
          item.type.includes(file?.name.slice(file?.name.lastIndexOf('.') + 1).toLowerCase()) &&
          file.size / 1024 / 1024 > item.size
      );
      if (overFile) {
        message.error(t(`common.upload.overSizeTip`, { name: overFile.name, size: overFile.size }));
        setSubLoading(false);
        return false;
      }
    }
    // 其他文件不能超过10MB
    if (
      props.otherFileLimit.every(
        (item) =>
          !item.type.includes(file?.name.slice(file?.name.lastIndexOf('.') + 1).toLowerCase())
      )
    ) {
      const isLt = file.size / 1024 / 1024 <= props.fileSize;
      if (!isLt) {
        message.error(`${t('common.upload.uploadSizeTip')} ${props.fileSize}MB`);
        setSubLoading(false);
        return false;
      }
    }
    // setSubLoading(false);
    return true;
  };

  // 上传前校检格式和大小
  const handleBeforeUpload = ({ file }) => {
    setSubLoading(true);
    const checkRes = checkFileTypeFn(file.file);
    if (checkRes) {
      setSubLoading(false);
    }
    return checkRes;
  };

  const handleChange = (options) => {
    if (options.fileList.every((item) => ['error', 'finished'].includes(item.status))) {
      setSubLoading(false);
    }
    if (props.isImportData) {
      fileList.value = options.file.status !== 'removed' ? [options.file] : [];
    }
  };

  //上传完成
  const finishFn = () => {
    // setSubLoading(false);
  };

  // 上传失败
  const handleUploadError = () => {
    setSubLoading(false);
    message.error(
      props.isImportData ? t('common.tipMsg.importFail') : t('common.tipMsg.uploadFail')
    );
  };

  //移除文件
  const handleFileRemove = ({ file }) => {
    const removeFileIndex = fileList.value.findIndex((item) => item.id === file.id);
    if (removeFileIndex > -1) {
      fileList.value.splice(removeFileIndex, 1);
    }
  };

  //自定义上传行为
  const customRequest = ({
    file,
    action,
    onFinish,
    onError,
    onProgress,
  }: UploadCustomRequestOptions) => {
    if (action && file) {
      setSubLoading(true);
      const form = new FormData();
      form.append('file', file.file as string | Blob);

      http
        .request(
          {
            url: action,
            method: 'post',
            responseType: 'blob',
            headers: {
              'Content-Type': 'multipart/form-data',
              isUploadFile: true,
            },
            data: form,
            onUploadProgress: ({ progress }) => {
              onProgress({ percent: Math.ceil(progress * 100) });
            },
          },
          { isUploadFile: true }
        )
        .then((res) => {
          if (props.isImportData) {
            setSubLoading(false);
          }
          if (res.code) {
            onFinish();
          } else if (res.data.type === 'application/json') {
            const reader = new FileReader();

            reader.readAsText(res.data, 'utf-8');

            reader.onload = async () => {
              const { code, message: msg, row } = JSON.parse(reader.result as string);

              if (code === 0) {
                await onFinish();
                if (props.isImportData) {
                  message.success(t('common.tipMsg.import'));
                  closeModalFn();
                  emit('getAttachmentList');
                } else {
                  fileList.value.push({
                    name: file.name,
                    id: file.id,
                    fileName: file.name,
                    fileType: file.type,
                    realUrl: row.realUrl,
                    temUrl: row.temUrl,
                  });
                }
              } else {
                message.error(msg);
              }
            };
          } else {
            clearFileList();
          }
        })
        .catch((err) => {
          console.log('upload err', err);
          if (props.isImportData) {
            setSubLoading(false);
          }
          onError();
        });
    }
  };

  const setSubLoadingFn = (flag: boolean) => {
    setSubLoading(flag);
  };

  // 关闭弹窗
  const closeModalFn = () => {
    try {
      setSubLoading(false);
      clearFileList();
      closeModal();
    } catch (err) {
      console.log('err', err);
    }
  };

  // 下载模板
  const downloadImportTemplateFn = async () => {
    if (!downloadImportRequest.value) {
      try {
        downloadImportRequest.value = true;

        await downLoadFile({
            type: unref(computedImportTemplateFileType),
            fileName: downloadNameFn(unref(computedImportTemplateFileName)),
            getDownloadUrl: '/oss/file/download/template',
          });
      } catch (e) {
        console.log(e);
      }

      downloadImportRequest.value = false;
    }
  };

  // 下载模板
  // const importTemplate = async () => {
  //   try {
  //     let data: any = await downLoadFile2(unref(computedImportTemplateDownloadName));

  //     if (data && data.code) {
  //       message.error(data.message);
  //       return false;
  //     }
  //     let blob = new Blob([data]);
  //     let url = window.URL.createObjectURL(blob);
  //     let link = document.createElement('a');
  //     link.style.display = 'none';
  //     link.download = unref(computedImportTemplateDownloadName);
  //     link.href = url;
  //     document.body.appendChild(link);
  //     link.click();
  //     document.body.removeChild(link);
  //     URL.revokeObjectURL(link.href);
  //   } catch (e) {
  //     console.log(e);
  //   }
  // };
  // 清空文件列表
  const clearFileList = () => {
    uploadDialog.value.clear();
    fileList.value = [];
  };
  // 获取文件名称
  const getFileName = (name) => {
    if (name.lastIndexOf('/') > -1) {
      return name.slice(name.lastIndexOf('/') + 1).toLowerCase();
    } else {
      return '';
    }
  };

  const openDialog = async (title?: string) => {
    const titleText = title
      ? title
      : props.isImportData
      ? t('common.upload.importData')
      : t('common.upload.uploadAttachment');
    openModal('', titleText);
    Ititle.value = titleText;
  };

  defineExpose({ openDialog, clearFileList, getFileName, closeModalFn, setSubLoadingFn });
</script>
<style lang="less" scoped>
  .upload-dialog-tip {
    background: #ffffff;
    padding: 0;
    // margin-top: 16px;
    margin-bottom: 15px;
  }
  .upload-dialog-tip p {
    color: #999999;
    padding-left: 0;
  }
  .upload-dialog-tip p:first-child {
    margin: 10px 0 20px 0;
  }
  .upload-dialog-tip p:last-child {
    margin: 12px 0;
  }
  .import-template {
    font-size: 14px;
    font-weight: 400;
    // text-decoration: underline;
    color: #1d6eff;
    cursor: pointer;
    &:hover {
      color: #185fdb;
      text-decoration: underline;
    }
  }
  .upload-dialog-tip {
    display: flex;
    font-size: 14px;
    font-weight: 400;
    text-align: left;
    color: #3d3d3d;
    line-height: 24px;

    &.import-dialog-tip {
      padding: 0;
      background: transparent;
      color: #999999;
      margin-bottom: 8px;
      // .content-right li:first-child {
      //   // margin: 10px 0 10px 0;
      // }
    }
    .content-left {
      // width: 88px;
      text-align: right;
      > div {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .el-icon-warning {
          font-size: 16px;
          margin-right: 8px;
          &::before {
            color: #1d6eff;
          }
        }
      }
    }
    .content-right {
      flex: 1;
      padding-left: 16px;
      li {
        list-style: decimal;
        word-break: break-word;
      }
    }
    .import-template {
      font-size: 14px;
      font-weight: 400;
      color: #1d6eff;
      cursor: pointer;
      word-break: keep-all;
      &:hover {
        text-decoration: underline;
      }
    }
  }

  .break-word {
    display: block;
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    .button-style {
      margin-left: 20px;
    }
  }
  .up-box {
    :deep(.n-button) {
      min-width: auto;
      padding: 0 3px;
    }
    .n-upload-dragger {
      width: 100%;
      // height: 180px;
      background: #fafafa;
      border: 1px dashed #d4d6d9;
      border-radius: 8px;
      &:hover {
        border-color: #307AFA;
      }
      .upload-icon {
        width: 65px;
        height: 65px;
        margin: 29px auto 16px;
      }
      .upload-text {
        font-size: 14px;
        color: #31373d;
        margin-bottom: 31px;
        span {
          color: #1d6eff;
        }
      }
    }

    :deep(
        .n-upload-file-list
          .n-upload-file.n-upload-file--with-url
          .n-upload-file-info
          .n-upload-file-info__name
          a
      ) {
      pointer-events: none !important;
    }
    :deep(.n-upload-file-list .n-upload-file.n-upload-file--with-url) {
      cursor: default;
    }
  }

  .content-right {
    flex: 1;
    padding-left: 16px;
    li {
      list-style: decimal;
      word-break: break-word;
    }
  }
</style>
